package com.qn.example.controller;

import com.qn.example.pojo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 21276
 * @version 1.0
 * @date 2023/5/10 16:07
 */
@RestController
@Slf4j
@RequestMapping("/common")
@CrossOrigin
public class CommonController {

    @Value("${reggie.path}")
    private String path;

    /**
     * url: http://localhost:8080/common/upload
     * 上传成功之后要返回文件名
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //1. 获取文件名
        String filename = file.getOriginalFilename(); //3 .jpg

        //2. 截取后缀名
        String extName = filename.substring(filename.lastIndexOf("."));
        //3. 使用UUID重新构建一个新的名字  UUID是有当前毫秒值+cpu序列号算出的全球唯一的值
        String uuidFileName=  UUID.randomUUID().toString()+extName;


        //2. 构建文件存储的目录
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }

        //目标文件   目录+文件名  G:/imgs/filename
        File targetFile = new File(dir,uuidFileName);
        //把上传的文件拷贝到目标文件上(本质上其实就是以前你们学习的io流拷贝文件 )
        file.transferTo(targetFile);

        return R.success(uuidFileName);
    }

    /**
     * 目标： 读取图片资源，然后向浏览器输出
     *
     */
    @GetMapping("/download")
    public  void download(String name, HttpServletResponse response) throws IOException {
        //1. 找到目标文件
        File targetFile = new File(path,name);
        //2. 建立文件输入流，
        FileInputStream fileInputStream = new FileInputStream(targetFile);
        //得到响应的输出流
        ServletOutputStream outputStream = response.getOutputStream();

        byte[] buf = new byte[1024];
        int length =0;
        //边读边写

        while((length=fileInputStream.read(buf))!=-1){
            outputStream.write(buf,0,length);
        }

        fileInputStream.close();
    }
}
